package com.qipa.netty.heartbeat;

import com.qipa.netty.heartbeat.ChannelMapObject;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.socket.SocketChannel;
import org.apache.log4j.Logger;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 心跳辅助类，存储会话
 * Created by Ethan on 2018/11/21.
 */
public class NettyChannelMap {

    static Logger logger = Logger.getLogger(NettyChannelMap.class);

    private static Map<String, ChannelMapObject> map = new ConcurrentHashMap<>();

    public static Map<String, ChannelMapObject> getMap() {
        return map;
    }

    public static void setMap(Map<String, ChannelMapObject> map) {
        NettyChannelMap.map = map;
    }

    /**
     * 添加连接
     * @param clientId
     * @param obj
     */
    public static void add(String clientId, ChannelMapObject obj) {
        logger.info("添加连接之前，连接数："+map.size());
        map.put(clientId, obj);
        logger.info("添加连接之后，连接数："+map.size());
    }

    public static Channel getChannel(String clientId) {
        ChannelMapObject channelMapObject = map.get(clientId);
        return channelMapObject.getSocketChannel();

    }

    public static Channel getChannel(SocketChannel socketChannel) {
        for (Map.Entry entry : map.entrySet()) {
            SocketChannel channel = ((ChannelMapObject) entry.getValue()).getSocketChannel();
            if(channel == socketChannel){
                return channel;
            }
        }
        return null;
    }

    /**
     * 关闭连接
     * @param socketChannel
     */
    public static void remove(SocketChannel socketChannel) {
        //关闭某个连接  保存的所有进来的连接
        for (Map.Entry entry : map.entrySet()) {
            SocketChannel channel = ((ChannelMapObject) entry.getValue()).getSocketChannel();
            if (channel == socketChannel) {
                System.out.println("关闭这个不活跃通道！："+channel);
                channel.close();
                map.remove(entry.getKey());
            }
        }
        //关闭单独存websocket连接的map
        Map<String, List<Channel>> channelsMap = WebSocketChannelMap.getChannels();
        for(Map.Entry entry: channelsMap.entrySet()){
            List<Channel> channels = (List<Channel>)entry.getValue();
            for (Channel channel : channels) {
                if (channel == socketChannel) {
                    System.out.println("关闭这个不活跃通道！："+channel);
                    channel.close();
                    channels.remove(channel);
                }
            }
        }
    }

    public static ChannelMapObject getMapObject(SocketChannel socketChannel) {
        for (Map.Entry entry : map.entrySet()) {
            ChannelMapObject object = (ChannelMapObject) entry.getValue();
            SocketChannel channel = object.getSocketChannel();
            if (channel == socketChannel)
                return object;
        }
        return null;
    }

}
